package org.totoro.concurrent.juc.sync;

import java.util.concurrent.CountDownLatch;

/**
 * 计数器
 *
 * @author YHL
 * @version V1.0
 * @Description: CountDownLatch 计数器
 * @date 2018-06-20
 */
public class CountDownLatchTest {


    /**
     * 比如有一个任务A，它要等待其他4个任务执行完毕之后才能执行，此时就可以利用CountDownLatch来实现这种功能了。
     *
     * @param args
     */
    public static void main(String[] args) {


        /**
         * 其实是 设置了  node 的 status = count
         */


        Integer count = 10;

        final CountDownLatch latch = new CountDownLatch(count);

        String threadName = "theradA";


        for (Integer i = 0; i < count; i++) {
            new Thread(() -> {
                try {

                    Thread thread = Thread.currentThread();
                    System.out.println(thread.getName() + "正在执行");

                    double random = Math.random();
                    Thread.sleep(Double.valueOf(String.valueOf(random * 1000)).longValue());
                    System.out.println(thread.getName() + "执行完毕");

                    /**
                     * status - 1
                     * 当 status = 0的时候，进行唤醒线程操作
                     */
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, threadName + i).start();
        }


        try {

            System.out.println("等待 latch 处理完毕...");
            latch.await();
            System.out.println(Thread.currentThread().getName() + " 监控到 latch已经处理完毕 .... ");

            System.out.println("继续执行" + Thread.currentThread().getName() + "...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
